<?php
namespace app\money\controller;
use app\admin\common\Base;
use think\Db;
//核销单
class Verifica extends Base
{

   public function index()
    {
        $data = $this->request->param();

        $this->assign('o_type',12);//高级搜索状态（12：核销单记录）

        $month = $this->get_month_start_to_end();
        $this->assign('month', $month);
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map='';
            $search=[];
            $where=[];
            $where1=[];//防覆盖
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
                $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
            } else {
                $month = $this->get_month_start_to_end();
            }

             //备注
            // if (isset($data['mark']) && $data['mark'] != '') {
            //      $search['mark'] =['like',"%".$data['mark']."%"]; 
            // }
            //客户
            // if (isset($data['user_id']) && $data['user_id'] != '') {
            //     $where['user_id']= ['in', $data['user_id']];
            // }
            //  //客户类别
         
            // if (!isset($data['customer_category_id']) || $data['customer_category_id'] == 0 || $data['customer_category_id'] == '') {
            // } else {
            //     $c = Db::name('customer')->where('category_id', $data['customer_category_id'])->select();
            //     $c['ids'] = implode(',', array_column($c, 'id'));
            //     $where1['user_id']= ['in',$c['ids']];//客户类别
            // }
           
            if ($map == '') {
                $list = Db::name('hexiao')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('hexiao')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('hexiao')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('hexiao')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }

            foreach ($list as $key => &$val) {
               
                $val['dj_time'] = date('Y-m-d', $val['dj_time']);
                $c = Db::name('customer')->where('id', $val['user_id'])->find();
                $val['customer_name'] = $c['sn'] . ' ' . $c['name'];
                $supplier = Db::name('customer')->where('id', $val['supplier_id'])->find();
                $val['supplier_name'] = $supplier['sn'] . ' ' . $supplier['name'];
                $val['add_user_name'] = $val['add_user'] == 0 ? '' : Db::name('auth_user')->where('id', $val['add_user'])->value('name');
                //$val['shenhe_user_name'] = $val['shenhe_user'] == 0 ? '' : Db::name('auth_user')->where('id', $val['shenhe_user'])->value('name');
                $val['type_name'] = $this->type_name($val['type']);
               
            }
            //halt($list);
            return $this->grid_data($list, $count, $page, $limit);
        }
        $today=date('Y-m-d',time());
        $mon_start=date('Y-m',time()).'-01';
        $this->assign('today',$today);
        $this->assign('mon_start',$mon_start);
      
        return $this->fetch();
    }


       //核销单详情
    public function details()
    {
        $data = $this->request->param();
        $oid = $data['id'];
        $o = Db::name('hexiao')->where('id', $oid)->where('is_del', 0)->find();
        $customer = Db::name('customer')->where('id', $o['user_id'])->find();
        $o['customer_name'] = $customer['sn'] . ' ' . $customer['name'];
        $o['type_name'] = $this->type_name($o['type']);
       
        // if ($o['xht_id'] == 0 & $o['xh_id'] == 0) { //判断是否已经生成销售单
        //     $o['create_o'] = 0;
        // } else {
        //     $o['create_o'] = 1;
        // }
        //halt($o);
        if (isset($data['ajax']) && $data['ajax'] == 100 && $data['tab']==1) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);


            if ($map == '') {
                $list = Db::name('hexiao_good')->where('pid', $oid)->where('position', 1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('addtime desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('hexiao_good')->where('pid', $oid)->where('position', 1)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('hexiao_good')->where('pid', $oid)->where('position', 1)->where('is_del', 0)->order('sort desc,id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                $count = Db::name('hexiao_good')->where('pid', $oid)->where('position', 1)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }

            foreach ($list as $key => &$val) {
                $val['psn'] = $val['o_sn'];
                $skd=Db::name('payment')->where('id',$val['o_id'])->where('sn',$val['o_sn'])->where('is_del', 0)->find();
                $val['type_name'] = "收款";
                $val['dj_time']=date('Y-m-d',$skd['dj_time']);
                $val['jine'] = sprintf("%.2f", floatval($skd['jine'])); //
                $val['already_jine'] =sprintf("%.2f", floatval($skd['hexiao_jine'])); //核销总金额
                $val['not_jine'] =sprintf("%.2f", floatval($skd['now_jine'])); //本次预收款
                $val['oid'] = $val['id'];
                //$val['now_jine'] = 

            }
            //少于4条则填充
            if (4 - $count > 0) {
                for ($i = 0; $i < 4 - $count; $i++) {
                    array_push($list, []);
                }
            }

            return $this->grid_data($list, $count, $page, $limit);
        }
        if (isset($data['ajax']) && $data['ajax'] == 100 && $data['tab']==2) {
        
            $map='';
            $page=isset($data['page'])?$data['page']:1;
            $page=intval($page);
            $limit=isset($data['rows'])?$data['rows']:10;
            $limit=intval($limit);
            $start=$limit*($page-1);

        
            if ($map == '') {
                $list = Db::name('hexiao_good')->where('pid', $oid)->where('position', 0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('addtime desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('hexiao_good')->where('pid', $oid)->where('position', 0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('hexiao_good')->where('pid', $oid)->where('position', 0)->where('is_del', 0)->order('sort desc,id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                $count = Db::name('hexiao_good')->where('pid', $oid)->where('position', 0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }

            foreach ($list as $key => &$val) {
                if(isset($val['o_id'])&&isset($val['o_sn'])){
                    $g=Db::name('order')->where('id',$val['o_id'])->where('sn',$val['o_sn'])->find();//订单
                    $val['psn']=$val['o_sn'];
                   
                 
                    
                   
                    $val['already_jine'] = floatval('0.00');
                   // $val['not_jine'] = $g['dj_jine'] - $g['already_jine'];
                    $val['type_name']=$g['o_type']==1? "普通销售" : "销售退回";
                    $val['dj_time']=date('Y-m-d',$g['dj_time']);
                    $val['dj_jine']=$g['o_type']==1?floatval($g['yh_price'])-floatval($g['payment']) : floatval($g['payment'])-floatval($g['yh_price']);
                    $val['jine']=sprintf("%.2f",$val['dj_jine']);
                    $val['already_jine']=floatval('0.00');
                    $val['not_jine']=$val['dj_jine']-$val['already_jine'];
                   // $val['shuliang']=$val['num'];
                   // $val['dw_name']=Db::name('unit')->where('id',$val['dw'])->value('name');

                }
                // 
                // 
                // $val['type_name']=$g['o_type']==1? "普通销售" : "销售退回";
                // $val['dj_time']=date('Y-m-d',$g['dj_time']);
                // $val['dj_jine']=$g['o_type']==1?floatval($g['yh_price'])-floatval($g['payment']) : floatval($g['payment'])-floatval($g['yh_price']);
                // $val['already_jine']=floatval('0.00');
                // $val['not_jine']=$g['dj_jine']-$g['already_jine'];
                // $val['shuliang']=$val['num'];
                // $val['dw_name']=Db::name('unit')->where('id',$val['dw'])->value('name');
            
            }
            //少于5条则填充
            if(5-$count>0){
                for ($i=0; $i <5-$count ; $i++) { 
                    array_push($list, []);
                }
            }
          
            return $this->grid_data($list,$count,$page,$limit); 
        }
        $this->assign('info', $o);
        $this->assign('admin', $this->Userinfo);
        return $this->fetch();
    }

    //1预收冲应收；2预付冲应付；3应收冲应付；4应收转应收；5：应付转应付
    public function type_name($type)
    {
        $type_name="其它";
        switch ($type) {
            case '1':
                $type_name="预收冲应收";   
                break;
            case '2':
                $type_name="预付冲应付";   
                break;
            case '3':
                $type_name="应收冲应付";   
                break;
            case '4':
                $type_name="应收转应收";   
                break;
            case '5':
                $type_name="应付转应付";   
                break;
              
            default:
                
                break;
        }
        return $type_name;
    }



    public function add()
    {
        $data = $this->request->param();
        $today=date('Y-m-d',time());
        $this->assign('today',$today);
        return $this->fetch();
    }


    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();

        //halt($data);
        Db::startTrans(); // 启动事务
        $res=$this->inset_hexiao_record($data);
        if($res==1){
            Db::commit();// 提交事务
            $status = 1;
            $msg = "添加成功";
        }else if($res==2){
            Db::rollback();// 回滚事务
            $msg = "存在相同的单据号";
        }else{
            Db::rollback();// 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    }

       // 公共方法 新增收(付)款单
    //($data数据，$t为类型1位入库单，0为入库，1为出库)
    //$w入库方式：0，采购入库；1，销售退货入库；2，调拨单入库；3，其它入库单入库；4，核销单入库
    //$w出库方式：0采购退货，1，销售，2调拨 3其它 4核销
    //data['sn','dj_time']
    //return 0,失败 1,成功 2,存在相同的单据号
    public function inset_hexiao_record($data)
    {

        $status = 0;
        $msg = "操作失败";
        $post = $data;

        $gooddata = $data['gooddata']; //源单1
        $accountdata=$data['accountdata'];//源单2
        unset($data['gooddata']);
        unset($data['accountdata']); 
        $info = Db::name('hexiao')->where('sn', $post['sn'])->where('is_del', 0)->find();
        if (!empty($info)) {
            // $msg = "存在相同的单据号";
            return 2;
        }
        $data['status'] = 1;//不需要审核
        $data['addtime'] = time();
        $data['updatetime'] = time();
        $data['enterprise_id'] = $this->EnterpriseId;
        $data['add_user'] = $this->Userinfo['id'];
        $data['dj_time'] = strtotime($data['dj_time']);
        $data['last_user'] = $this->Userinfo['id'];
        $insert_id = Db::name('hexiao')->insertGetId($data);
        //添加子表
        if ($insert_id) {

            $post['pid'] = $insert_id; //父id
            $post['psn'] = $data['sn']; //父sn
            $post['enterprise_id'] = $this->EnterpriseId;
            //更新附表
            //更新字表
                $arr = [];
                foreach ($gooddata as $key => $val) {

                    if (isset($val['oid']) && intval($val['oid']) != 0) {
                        $ins = [
                            'addtime' => time(),
                            'updatetime' => time(),
                            'pid' => $insert_id,
                            'enterprise_id' => $this->EnterpriseId,
                            'o_id' => intval($val['oid']), //源单ID
                            'o_sn' => $val['psn'], //源单sn
                            'price' => $val['now_jine'], //本次核销金额
                            'type' => $data['type'], //
                            'position'=>0,
                            'now_jine'=>$val['now_jine'],
                          
                        ];
                        array_push($arr, $ins);
                        //设置订单为核销过
                        $is_hexiao = $this->order_is_hexiao($val['oid']);
                        if ($is_hexiao != 1) {
                            return 0;
                        }
                    }
                }
                 foreach ($accountdata as $key => $val) {

                    if (isset($val['oid']) && intval($val['oid']) != 0) {
                        $ins = [
                            'addtime' => time(),
                            'updatetime' => time(),
                            'pid' => $insert_id,
                            'enterprise_id' => $this->EnterpriseId,
                            'o_id' => intval($val['oid']), //源单ID
                            'o_sn' => $val['psn'], //源单sn
                            'price' => $val['now_jine'], //本次核销金额
                            'type' => $data['type'], //
                            'position'=>1,
                            'now_jine'=>$val['now_jine'],
                          
                        ];
                        array_push($arr, $ins);
                        //设置订单为核销过
                        $is_hexiao = $this->payment_is_hexiao($val['oid']);
                        if ($is_hexiao != 1) {
                            return 0;
                        }
                    }
                }
                if (count($arr) > 0) {
                    $res = Db::name('hexiao_good')->insertAll($arr);
                    if ($res) {
                        return 1;
                    }
                } else { //无关联单
                    return 1;
                }
        }
        return 0;
    }


    // public function edit()
    // {
    //     $data = $this->request->param();
       
    //     return $this->fetch();
    // }

        //核销掉订单
    public function payment_is_hexiao($oid)
    {
        $update = [
            'is_hx' => 1,
            'updatetime' => time(),
            'last_user' => $this->Userinfo['id'],
        ];
        //设置订单为核销过
        $res = Db::name('payment')->where('id', $oid)->where('is_del', 0)->update($update);
        if ($res) {
            return 1;
        }
        return 0;
    }


   



}
